<template>
  <div>
    <el-drawer :title="title" :visible.sync="dialog" direction="rtl" ref="drawer" size="45%" :destroy-on-close="true"
      :before-close="close" :wrapperClosable="false">
      <el-form ref="createUserForm" :model="formData" :rules="rules" size="small" label-width="110px">
        <br />
        <el-form-item label="商品名称" prop="productName">
          <el-input v-model="formData.productName" placeholder="请输入商品名称	" clearable :style="{width: '100%'}">
          </el-input>
        </el-form-item>
        <el-form-item label="商品编号" prop="productNo">
          <el-input v-model="formData.productNo" placeholder="请输入商品编号	" clearable :style="{width: '100%'}">
          </el-input>
        </el-form-item>
        <el-form-item label="商品原价" prop="productPrice">
          <el-input v-model="formData.productPrice" type="number" placeholder="请输入商品原价	" clearable :style="{width: '100%'}">
          </el-input>
        </el-form-item>
        <el-form-item label="活动优惠价格" prop="productDiscount">
          <el-input v-model="formData.productDiscount" type="number" placeholder="请输入活动优惠价格" clearable :style="{width: '100%'}">
          </el-input>
        </el-form-item>
        <el-form-item label="封面图" prop="coverUrl">
          <el-upload :class="{ disabled: uploadDisabled }" :limit="1" class="pic-div" ref="fileIdStrRef"
            list-type="picture-card" action="" :multiple="false" accept="image/*" :file-list="fileList"
            :http-request="uploadHttpRequest" :on-success="uploadOnSuccess" :before-upload="beforeUpload"
            :on-error="uploadOnError" :on-remove="uploadOnRemove">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品描述" prop="productContent">
          <div id="articleHtml" v-model="formData.productContent"></div>
        </el-form-item>

      </el-form>
      <div class="el-drawer-footer">
        <el-button size="small" @click="dialog = false">取 消</el-button>
        <el-button type="primary" size="small" @click="submitForm" :loading="loading">{{ loading ? '提交中 ...' : '提 交' }}
        </el-button>
      </div>
    </el-drawer>
  </div>
</template>

<script>
  // 引入 wangEditor 富文本编辑器
  import E from "wangeditor"
  import {
    imgUpload
  } from '@/api/upload'
  import {
    addProduct,
    updateProduct,
    getProductInfo,
  } from '@/api/mall.product.js'
  import {
    API_HOST
  } from '@/constant'
  export default {
    data() {
      return {
        dialog: false,
        loading: false,

        formData: {
          productAppointmentId: undefined,
          productName: undefined,
          productNo: undefined,
          productTags: undefined,
          productPrice: undefined,
          productDiscount: undefined,
          productContent: undefined,
          coverUrl: undefined
        },
        rules: {
          productName: [{
            required: true,
            message: '请输入商品名称	',
            trigger: 'blur'
          }],
          productNo: [{
            required: true,
            message: '请输入商品编号	',
            trigger: 'blur'
          }],
          productPrice: [{
            required: true,
            message: '请输入商品原价	',
            trigger: 'blur'
          }],
          productDiscount: [{
            required: true,
            message: '请输入活动优惠价格',
            trigger: 'blur'
          }],
          coverUrl: [{
            required: true,
            message: '请上传封面',
            trigger: 'blur'
          }],
          productContent: [{
            required: true,
            message: '请输入商品描述',
            trigger: 'blur'
          }]
        },
        fileList: [],
        editor: null
      }
    },
    computed: {
      title() {
        return this.formData.productAppointmentId ? '编辑商品' : '新增商品'
      },
      uploadDisabled() {
        return this.fileList.length > 0 //判断图片上传的数量动态控制按钮隐藏与显示
      },
    },
    mounted() {

    },
    methods: {
      close() {
        this.loading = false;
        this.dialog = false;
        this.resetForm();
      },
      async open(productAppointmentId) {
        this.resetForm();
        this.loading = false;
        this.dialog = true;
        if (productAppointmentId) {
          this.formData.productAppointmentId = productAppointmentId
          var res = await getProductInfo(productAppointmentId);
          var data = res.data;
          for (let key in this.formData) {
            if (data.hasOwnProperty(key)) {
              this.formData[key] = data[key];
            }
          }
          this.fileList.push({
            name: null,
            url: res.data.coverUrl,
            fileId: null
          });
          // this.editor.txt.html(res.data.productContent);
        } else {
          if (this.editor != null && this.editor != undefined) {
            this.editor.destroy();
            this.editor = null;
          }
          this.formData.productAppointmentId = '';
        }
        this.createEditor()
      },
      // 创建富文本对象
      createEditor() {
        if (this.editor == null) {
          this.$nextTick(() => {
            var editor = new E('#articleHtml');
            editor.config.showLinkImg = false; // 去掉网络图片地址插入模式
            editor.config.height = 450; // 设置高度
            editor.config.uploadImgServer = API_HOST + 'fileInfo/uploadImg'; // 上传图片的接口地址
            editor.config.uploadFileName = 'file'; // formdata中的name属性
            editor.config.uploadImgHooks = {
              fail: (xhr, editor, result) => {
                // 插入图片失败回调
              },
              success: (xhr, editor, result) => {
                // 图片上传成功回调
              },
              timeout: (xhr, editor) => {
                // 网络超时的回调
              },
              error: (xhr, editor) => {
                // 图片上传错误的回调
              },
              customInsert: (insertImg, result, editor) => {
                // 将图片填充到富文本编辑区
                insertImg(result.data)
              }
            }
            editor.config.onchange = (html) => {
              this.formData.productContent = html
            }
            editor.create();
            this.editor = editor;
          })
        }
      },

      submitForm() {
        this.$refs.createUserForm.validate(async valid => {
          if (!valid) return

          this.loading = true;
          try {
            var data = Object.assign({}, this.formData);
            var res;
            if (data.productAppointmentId) {
              //修改
              res = await updateProduct(data);
            } else {
              //添加
              res = await addProduct(data);
            }
            this.$utils.showSuccessMessage(res.msg, () => {
              this.close();
              this.$parent.searchTable();
            });
          } finally {
            this.loading = false;
          }
        })
      },

      resetForm() {
        if (this.$refs.createUserForm !== undefined) {
          this.$refs.createUserForm.resetFields();
        }
        this.fileList = [];
        this.formData.coverUrl = '';
        if (this.editor != null && this.editor != undefined) {
          this.editor.txt.html('');
        }
      },

      //上传文件
      async uploadHttpRequest(data) {
        var formData = new FormData();
        formData.append('file', data.file);
        formData.append('fileName', data.file.name);
        var res = await imgUpload(formData);
        return res.data;
      },
      uploadOnSuccess(response, file, fileList) {
        this.setFileIdStr(fileList);
      },
      uploadOnError(err, file, fileList) {
        this.setFileIdStr(fileList);
      },
      uploadOnRemove(file, fileList) {
        this.setFileIdStr(fileList);
      },
      beforeUpload(file) {
        const isLt2M = file.size / 1024 / 1024 < 2
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isLt2M
      },
      setFileIdStr(fileList) {
        var coverUrl = fileList.map(x => {
          if (x.hasOwnProperty('response')) {
            return x.response;
          } else {
            return x.url;
          }
        });
        this.formData.coverUrl = coverUrl[0];
        this.fileList = fileList;
      },

    }
  }
</script>

<style>
  .el-drawer__header {
    -webkit-box-align: center;
    -ms-flex-align: center;
    align-items: center;
    color: #72767b;
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    margin-bottom: 15px;
    padding: 15px 20px 0;
  }

  .el-drawer__body {
    height: calc(100% - 55px) !important;
    overflow-y: auto;
    padding: 5px;
    border-top: #DDDDDD 1px solid;
    margin-bottom: 62px;
    border-bottom: #DDDDDD 1px solid;
  }

  .el-drawer-footer {
    width: 100%;
    text-align: right;
    padding: 15px 20px;
    background-color: white;
    position: absolute;
    bottom: 0;
  }

  .disabled .el-upload--picture-card {
    display: none;
  }

</style>
